package rabbitmq.A08springboot;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
public class ExchangeTopicConsumer {
    /**
     * 创建交换机并且绑定队列1（绑定routingkey1）
     *
     * @param content 内容
     * @param channel 通道
     * @param message 消息
     * @throws IOException      ioexception
     * @throws TimeoutException 超时异常
     */
    @RabbitListener(bindings = {@QueueBinding(
            exchange = @Exchange(value = ExchangeTopicProducer.EXCHANGE_TOPIC, durable = "true", type = ExchangeTypes.TOPIC),
            value = @Queue(value = ExchangeTopicProducer.EXCHANGE_TOPIC_QUEUE_1, durable = "true"),
            key = ExchangeTopicProducer.EXCHANGE_TOPIC_ROUTING1_KEY_1
    )}, ackMode = "MANUAL")
    @RabbitHandler
    public void exchangeTopicRoutingKey1(String content, Channel channel, Message message) {
        try {
            log.info("来一次");

            if (message.getMessageProperties().isRedelivered()) {
                log.info("重发的消息就算了");
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);

            } else {
//            就完了
//            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
                //拒绝，并是否重发
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), true, true);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        log.info("#号统配符号队列1接收到消息:{}", content);
    }

    /**
     * 创建交换机并且绑定队列2（绑定routingkey2）
     */
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = ExchangeTopicProducer.EXCHANGE_TOPIC, durable = "true", type = ExchangeTypes.TOPIC),
            value = @Queue(value = ExchangeTopicProducer.EXCHANGE_TOPIC_QUEUE_2, durable = "true"),
            key = ExchangeTopicProducer.EXCHANGE_TOPIC_ROUTING2_KEY_2
    ))
    @RabbitHandler
    public void exchangeTopicRoutingKey2(String content, Channel channel, Message message) {
        log.info("*号统配符号队列2接收到消息:{}", content);
    }


}